﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using FMS.Formulation.Licensing.Engine;

namespace WindowsFormsApp1
{

    internal class TrialLicense
    {
        private const int TRIAL_EXPIRATION = 45;

        private const string MINIMUM_DATE = "01/01/1900";

        private DateTime _minimumDate;

        public TrialLicense()
        {
            _minimumDate = DateTime.ParseExact("01/01/1900", "MM/dd/yyyy", CultureInfo.InvariantCulture);
        }

        public bool LicenseIsATrial(string fileURL)
        {
            return false;
        }

        public bool LicenseIsATrial(XmlDocument xdoc)
        {
            return false;
        }

        public string GetLicenseData(XmlDocument xdoc, ref bool IsDisabled)
        {
            IsDisabled = true;
            XmlNodeList elementsByTagName = xdoc.GetElementsByTagName("Trial0");
            if (elementsByTagName.Count == 0)
            {
                return string.Empty;
            }
            try
            {
                string value = elementsByTagName.Item(0).ChildNodes.Item(0).Value;
                Encryption encryption = new Encryption();
                UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
                string text = encryption.DecodeString(value, 0);
                if (text.Length < 1)
                {
                    return string.Empty;
                }
                byte[] bytes = unicodeEncoding.GetBytes(text);
                string text2 = encryption.ComputeMD5HashString(bytes);
                if (text2.Length < 1)
                {
                    return string.Empty;
                }
                XmlNodeList elementsByTagName2 = xdoc.GetElementsByTagName("Trial1");
                if (elementsByTagName2.Count == 0)
                {
                    return string.Empty;
                }
                string value2 = elementsByTagName2.Item(0).ChildNodes.Item(0).Value;
                if (value2 != "Disabled")
                {
                    string text3 = Convert.ToBase64String(encryption.DecodeStringToByteArray(value2, 1));
                    if (text2 != text3)
                    {
                        return string.Empty;
                    }
                    IsDisabled = false;
                }
                return text;
            }
            catch
            {
                return string.Empty;
            }
        }

        public void WriteOutTrialLicenseFile(FMS.Formulation.Licensing.License.License theLicense, string fileURL)
        {
            XmlDocument xmlDocument = BuildTrialLicense(theLicense);
            xmlDocument.Save(fileURL);
        }

        private XmlDocument BuildTrialLicense(FMS.Formulation.Licensing.License.License theLicense)
        {
            DateTime dateTime = DateTime.Now.AddDays(45.0);
            if (theLicense.HasExpirationDate && theLicense.ExpirationDate < dateTime)
            {
                dateTime = theLicense.ExpirationDate;
            }
            string s = BuildLicenseString(theLicense, dateTime);
            Encryption encryption = new Encryption();
            UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
            byte[] bytes = unicodeEncoding.GetBytes(s);
            string innerText = encryption.EncodeByteArray(bytes, 0);
            byte[] inpArray = encryption.ComputeMD5Hash(bytes);
            string innerText2 = encryption.EncodeByteArray(inpArray, 1);
            XmlDocument xmlDocument = new XmlDocument();
            XmlDeclaration newChild = xmlDocument.CreateXmlDeclaration("1.0", null, null);
            xmlDocument.AppendChild(newChild);
            XmlElement xmlElement = xmlDocument.CreateElement("TrialLicense", "http://www.feedsys.com");
            xmlDocument.AppendChild(xmlElement);
            XmlElement xmlElement2 = xmlDocument.CreateElement("LicenseName", string.Empty);
            xmlElement.AppendChild(xmlElement2);
            xmlElement2.InnerText = theLicense.CompanyName;
            XmlElement xmlElement3 = xmlDocument.CreateElement("SerialNumber", string.Empty);
            xmlElement.AppendChild(xmlElement3);
            xmlElement3.InnerText = theLicense.LicenseSerialNumber.ToString();
            XmlElement xmlElement4 = xmlDocument.CreateElement("ExpirationDate", string.Empty);
            xmlElement.AppendChild(xmlElement4);
            xmlElement4.InnerText = dateTime.ToLongDateString();
            XmlElement xmlElement5 = xmlDocument.CreateElement("Trial0", string.Empty);
            xmlElement.AppendChild(xmlElement5);
            xmlElement5.InnerText = innerText;
            XmlElement xmlElement6 = xmlDocument.CreateElement("Trial1", string.Empty);
            xmlElement.AppendChild(xmlElement6);
            xmlElement6.InnerText = innerText2;
            return xmlDocument;
        }

        private string BuildLicenseString(FMS.Formulation.Licensing.License.License theLicense, DateTime ExpirationDateOverride)
        {
            string empty = string.Empty;
            StringBuilder stringBuilder = new StringBuilder();
            DateTime now = DateTime.Now;
            stringBuilder.Append("VerifyLicense = False\n");
            stringBuilder.Append("LastVerifiedDate = ");
            stringBuilder.Append(TranslateFromDate(now));
            stringBuilder.Append("\n");
            stringBuilder.Append("ActivationCode = \n");
            stringBuilder.Append("CName = " + theLicense.CompanyName.Trim() + "\n");
            stringBuilder.Append("TimeBomb = ");
            stringBuilder.Append(TranslateFromDate(ExpirationDateOverride));
            stringBuilder.Append("\n");
            stringBuilder.Append("PrevDate = ");
            stringBuilder.Append(TranslateFromDate(now));
            stringBuilder.Append("\n");
            stringBuilder.Append("SerialNum = " + theLicense.LicenseSerialNumber + "\n");
            stringBuilder.Append("MaxiSpec = " + theLicense.MaximumIngredientsInSpec + "\n");
            stringBuilder.Append("MaxNSpec = " + theLicense.MaximumNutrientsInSpec + "\n");
            stringBuilder.Append("NoNuts = " + theLicense.MaximumNutrientsInSystem + "\n");
            stringBuilder.Append("MaxIngs = " + theLicense.MaximumIngredientsInSystem + "\n");
            stringBuilder.Append("ArchOn = " + theLicense.MaximumArchiveVersionsAllowed + "\n");
            stringBuilder.Append("PlugNo = " + 45 + "\n");
            stringBuilder.Append("PlugSer = " + 45 + "\n");
            stringBuilder.Append("DisSwtch = False\n");
            stringBuilder.Append("MaxUsers = " + theLicense.MaximumUsers + "\n");
            stringBuilder.Append("MaxMult = " + theLicense.MaximumMultiblendUsers + "\n");
            stringBuilder.Append("MasterCo = " + theLicense.MasterCompany + "\n");
            stringBuilder.Append("CustID = " + theLicense.CustomerID.Trim() + "\n");
            stringBuilder.Append("CustIDDesc = " + theLicense.CustomerIDDescription.Trim() + "\n");
            stringBuilder.Append("Comment = " + theLicense.Comment.Trim() + "\n");
            stringBuilder.Append("AppVer = " + theLicense.ApplicationVersion + "\n");
            int num = 200;
            for (int i = 0; i <= num; i++)
            {
                if (theLicense.Switches.Contains(i))
                {
                    stringBuilder.Append($"Switch #{i:000}: ");
                    if (theLicense.Switches[i].HasExpirationDate)
                    {
                        stringBuilder.Append($"{theLicense.Switches[i].ExpirationDate:yyyy-MM-dd} ");
                    }
                    else
                    {
                        stringBuilder.Append(string.Format("{0}               ", "Yes"));
                    }
                    stringBuilder.Append("\n");
                }
            }
            return stringBuilder.ToString();
        }

        public void DestroyTrialLicense(XmlDocument xdoc, string CertificateURL)
        {
            XmlNodeList elementsByTagName = xdoc.GetElementsByTagName("Trial1");
            if (elementsByTagName.Count > 0)
            {
                elementsByTagName.Item(0).ChildNodes.Item(0).Value = "Disabled";
            }
            xdoc.Save(CertificateURL);
        }

        private string TranslateFromDate(DateTime inDate)
        {
            return $"{inDate:yyyy-MM-dd}";
        }
    }

}
